package com.syj.qdp.framework.common.pojo;

import cn.hutool.core.lang.Assert;
import com.syj.qdp.framework.common.exception.ErrorCode;
import com.syj.qdp.framework.common.exception.ServiceException;
import com.syj.qdp.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 通用返回
 *
 * @author Lyon
 */
@ApiModel("结果集")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CommonResult<T> implements Serializable {

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 错误提示，用户可读
     */
    private String msg;

    /**
     * 数据
     */
    private T data;


    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(200, "", data);
    }

    public static <T> CommonResult<T> success() {
        return new CommonResult<T>(200, "", null);
    }

    public static <T> CommonResult<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> CommonResult<T> error(Integer code , String message) {
        Assert.isFalse(isSuccess(code), "必须是错误状态码");
        return new CommonResult<T>(code, message, null);
    }


    @JsonIgnore
    private static boolean isSuccess(Integer code) {
        return GlobalErrorCodeConstants.SUCCESS.getCode().equals(code);
    }

    public static <T> CommonResult<T> error(ServiceException serviceException) {
        return error(serviceException.getCode(), serviceException.getMessage());
    }



}
